package cn.aposoft.algorithms;

public class ZigZagAlgorithms {

    /**
     * convert the given integer following the variable-length zig-zag encoding
     *
     * @param value origin value
     * @return (value << 1) ^ (value >> 31)
     */
    public static int encode(final int value) {
        return (value << 1) ^ (value >> 31);
    }

    /**
     * convert the given integer following the variable-length zig-zag decoding
     *
     * @param value origin value
     * @return (value << 1) ^ (value >> 63)
     */
    public static long encode(final long value) {
        return (value << 1) ^ (value >> 63);
    }
    /**
     * convert the given integer following the variable-length zig-zag decoding
     *
     * @param value origin value
     * @return (value >>> 1) ^ -(value & 1)
     */
    public static int decode(final int value) {
        return (value >>> 1) ^ -(value & 1);
    }
    /**
     * convert the given integer following the variable-length zig-zag encoding
     *
     * @param value origin value
     * @return (value >>> 1) ^ -(value & 1)
     */
    public static long decode(final long value) {
        return (value >>> 1) ^ -(value & 1);
    }
}
